'''
# read data from TRC file into a 3-D matrix
# bryan conrad
# 2/20/2007
# returns f (the number of frames) as well as the full data set extracted
# from the TRC
# USAGE: [frames MkrData mkrName rate Header]=marker_data_read([TRC_path]);
#   if TRC_path is not specified, then a dialog will open to allow the user
#   to select a file.
#
#   format for MkrData is: datam(frame, marker, [x, y, z])

Created on Aug 7, 2009

@author: conrabp
'''
import os
import sys
import csv
import numpy as np

debug = True

try:
    from PyQt4 import QtGui
    use_qt = True
except:
    use_qt = False

    
def marker_data_read(trc_path=None):
    
#===============================================================================
# Open the File using gui if no file name was supplied      
#===============================================================================
    if (trc_path is None) and (use_qt is True):
        # user did not specify an path, so open a file dialog to get one
        app=QtGui.QApplication(sys.argv)
        dialog = QtGui.QFileDialog(None)
        trc_path = dialog.getOpenFileName(None,
                                          'Select a trc file to open',
                                          r'C:\Documents and Settings\conrabp\My Documents\Research\Motion Analysis\Sports Performance\Football\1129\Processed',
                                          '*.trc')
        if trc_path.isEmpty():
            print 'No File selected, exiting'
            return
        
        print 'Opening file: ', trc_path
    elif not os.path.isfile(trc_path):
        print 'Invalid filename provided, exiting'
        return
    #===============================================================================
    # Parse the data from file    
    #===============================================================================
    # headers and data are created as empty lists.
    headers = []
    trc_file = open(trc_path,'r')
    trc_reader = csv.reader(trc_file,delimiter='\t')
    # First read in the headers
    for row in range(6):
        headers.append(trc_reader.next())
    
    # Parse the markers from the header info
    marker_list = np.asarray(headers[3])
    marker_names = marker_list[np.arange(2,len(marker_list)-1,3)]      
    
    # Get Useful information from the header
    data_rate = float(headers[2][0])
    n_markers = int(headers[2][3])
    n_frames = int(headers[2][2])   
    
    # Create a numpy array based on the number of markers and number of frames
    data = np.zeros((n_frames,n_markers,3))
    
    # Once the headers are read, the rest of the file is data
    for frame,row in enumerate(trc_reader):
        for marker in range(n_markers):
            for dim in range(3):
                element = row[marker*3+dim+2]
                if element != '':
                    data[frame,marker,dim] = float(element)
                else:
                    data[frame,marker,dim] = np.nan
                    if debug:
                        print "At Frame %i: %s(%i) is a gap" % \
                              (frame+1,marker_names[marker],dim+1) 
            
            
    # We are done with the file, so lets close it
    trc_file.close()
    
    print 'Rate:       ', data_rate
    print 'Frames:     ', n_frames
    print '# Markers:  ', n_markers
    #assert(1.0/float(headers[2][0])==(float(data[1][0])-float(data[0][0]))) 
    #assert(int(headers[2][2])==len(data))
    return [n_frames, data, marker_names, data_rate, headers]


def test():
    pass



if __name__ == '__main__':
    marker_data_read(r'C:/Documents and Settings/conrabp/My Documents/Research/Motion Analysis/Sports Performance/Football/1129/Processed/1129cl2.trc')
#    marker_data_read()
